package com.ruoyi.system.socket;

import com.ruoyi.common.utils.StringUtils;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;

public class TcpClient {
    public static void main(String[] args) {
        String host = "127.0.0.1"; // 服务器地址
        int port = 2317; // 服务器端口
        try (Socket socket = new Socket(host, port);
             InputStream inputStream = socket.getInputStream();
             DataInputStream dataInputStream = new DataInputStream(inputStream)) {
            OutputStream ops = socket.getOutputStream();   // 打开输出流
//            while (true) {
                // 读取16进制字符串
                byte[] buffer = new byte[1024]; // 假设最多可以读取1024字节
                int bytesRead = dataInputStream.read(buffer);
                if (bytesRead > 0) {
                    String hexString = BinaryToHexString(buffer);
                    System.out.println("Received Hex String: " + hexString);
                }
                String hexString = "01 03 04 3F 2B B2 19 33 45"; // 需要发送的16进制字符串
                byte[] bytes = hexStrToBinaryStr(hexString);
                ops.write(bytes);
//            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static byte[] hexStrToBinaryStr(String hexString) {
        if (StringUtils.isEmpty(hexString)) {
            return null;
        }
        hexString = hexString.replaceAll(" ", "");
        int len = hexString.length();
        int index = 0;
        byte[] bytes = new byte[len / 2];
        while (index < len) {
            String sub = hexString.substring(index, index + 2);
            bytes[index / 2] = (byte) Integer.parseInt(sub, 16);
            index += 2;
        }
        return bytes;
    }

    public static String BinaryToHexString(byte[] bytes) {
        String hexStr = "0123456789ABCDEF";
        String result = "";
        String hex = "";
        for (byte b : bytes) {
            hex = String.valueOf(hexStr.charAt((b & 0xF0) >> 4));
            hex += String.valueOf(hexStr.charAt(b & 0x0F));
            result += hex + " ";
        }
        return result;
    }
}